package com.scalar.chiptrack.sales.actions;


import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.AddressForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;

public final class AddressAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/addAddress.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {

        AddressForm subform = ( AddressForm ) form;
		String action       = request.getParameter("action");

	    HttpSession session = request.getSession();
        User user           = ( User ) session.getAttribute (SessionKeys.USER_KEY);
        if( user == null )
        {
            //session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
            //return (mapping.findForward ("login"));
            request.setAttribute ( "closeWindowAfterSessionExp", "true" );
            return( mapping.findForward( "success" ) );
        }
		// Validate the request parameters specified by the user
		ActionErrors errors = new ActionErrors();
        HashMap errorsTemp  = new HashMap();
        HashMap errorsMap   = ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES );
        if( errorsMap == null )
        {
            errorsMap = new HashMap();
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errorsMap );
        }

        if( "AddShippingAddress".equals( action ) )
        {
            //Open the popup window...
             return( mapping.findForward( "success" ) );
        }

        if( "SaveShippingAddress".equals( action ) )
        {
            DBTransaction dbTransaction  = null;
            boolean success              = false;

            try
            {
                // Start transaction
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();

                int customerId = Integer.parseInt(request.getParameter("customerId"));

                //Insert the address details in the Address Table and get addressId
                int addressId = SalesOrderDAO.saveShippingAddress(dbTransaction,
                                    subform.getAddress1(),
                                    subform.getAddress2(),
                                    subform.getAddress3(),
                                    subform.getAddress4(),
                                    subform.getCity(),
                                    subform.getState(),
                                    subform.getZipCode(),
                                    subform.getCountry(),
                                    subform.getPhoneNumber(),
                                    subform.getFaxNumber(),
                                    subform.getEmail(),
                subform.getContactPerson(),
                subform.getCellNumber(), subform.getTagName() );
                //Insert the contact person details in address contact person table
                // CustomerDAO.insertContactPerson (dbTransaction, addressId, subform.getContactPerson(), subform.getPhoneNumber(),subform.getCellNumber(), subform.getFaxNumber() , subform.getEmail() , "", "Address" );
                if( !( "".equals( subform.getContactPerson() ) ) && !( Constants.SALES_INTEGRATION_TYPE_GREAT_PLAINS.equals( ConfigManager.getSalesIntegrationType() ) ) )
                {
                    CustomerDAO.insertContactPerson( dbTransaction, addressId, subform.getContactPerson(), subform.getPhoneNumber(),subform.getCellNumber(), subform.getFaxNumber() , subform.getEmail(),  subform.getSalesAckMail()  , subform.getShipAlerts() , subform.getproformaInvoice() ,subform.getpackingSlip() , subform.getcommerInvoice(), "", "Address", false, false);
                }
                //Insert the values in the customer shippingtable
                CustomerDAO.updateCustomerAddressTable( dbTransaction, customerId, addressId, "Shipping");

                success = true;

                session.setAttribute( "newShippingAddressId", Integer.toString( addressId ) );
                ArrayList shippingContactPersons = new ArrayList();
                shippingContactPersons.add( subform.getContactPerson() );
                session.setAttribute ( "shippingAddressContactPersons", shippingContactPersons );

                //This will add the newly added address to the shippingAddresses array list
                ArrayList shippingList = ( ArrayList ) session.getAttribute( "shippingAddresses" );
                String addrStr = "";

                if( shippingList == null )
                {
                    shippingList = new ArrayList();                            
                }

                //Added by sarada on 26th Jan 2004 to show contact person in address details
                if( ( subform.getContactPerson() != null )  && ( subform.getContactPerson().trim().length() != 0 ) )
                {
                    shippingList.add( new org.apache.struts.util.LabelValueBean( subform.getContactPerson(),Integer.toString(addressId )) );
                }

                if( ( subform.getAddress1() != null ) && ( subform.getAddress1().trim().length() != 0 ) )
                {
                    shippingList.add( new org.apache.struts.util.LabelValueBean( subform.getAddress1(),Integer.toString(addressId )) );
                }
                if( ( subform.getAddress2() != null )  && ( subform.getAddress2().trim().length() != 0 ) )
                {
                    shippingList.add( new org.apache.struts.util.LabelValueBean( subform.getAddress2()+",",Integer.toString( addressId )) );
                }
                if( ( subform.getAddress3() != null ) && ( subform.getAddress3().trim().length() != 0 ) )
                {
                    shippingList.add( new org.apache.struts.util.LabelValueBean( subform.getAddress3(),Integer.toString(addressId )) );
                }
                if( ( subform.getAddress4() != null )  && ( subform.getAddress4().trim().length() != 0 ) )
                {
                    shippingList.add( new org.apache.struts.util.LabelValueBean( subform.getAddress4()+",",Integer.toString( addressId )) );
                }
                if( ( subform.getCity() != null )  && ( subform.getCity().trim().length() != 0 ) )
                {
                    shippingList.add( new org.apache.struts.util.LabelValueBean( subform.getCity(),Integer.toString( addressId )) );
                }
                if( ( subform.getState() != null )  && ( subform.getState().trim().length() != 0 ) )
                {
                    if(addrStr.trim().length() !=0 )
                        addrStr = addrStr + " ," + subform.getState();
                    else
                        addrStr=subform.getState();
                }
                if( ( subform.getZipCode() != null )  && ( subform.getZipCode().trim().length() != 0 ) )
                {
                    if (addrStr.trim().length() !=0 )
                        addrStr = addrStr + " ," + subform.getZipCode();
                    else
                        addrStr=subform.getZipCode();
                }
                if( ( subform.getCountry() != null )  && ( subform.getCountry().trim().length() != 0 ) )
                {
                    if( addrStr.trim().length()!= 0 )
                        addrStr = addrStr + " ,"+subform.getCountry();
                    else
                        addrStr=subform.getCountry();
                }

                if( addrStr.trim().length() !=0 )
                    shippingList.add( new org.apache.struts.util.LabelValueBean(addrStr,Integer.toString( addressId )) );

                //Displaying a line after each address in the list
                shippingList.add(new org.apache.struts.util.LabelValueBean("    " , Integer.toString( addressId )));

                session.setAttribute( "shippingAddresses", shippingList );

                request.setAttribute( "closeWindow", "true" );
            }
            catch( ScalarException se )
            {
                /*String shippingMethodLabel = null;
                try
                {
                    shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                    if ( shippingMethodLabel == null )
                    {
                        shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                }
                errorsTemp.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+shippingMethodLabel+" Value." );*/
                //errorsTemp.put(ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SHIPPED_ORDER);

                errorsMap.put( "Error: Could not save new Shipping Address", null );

                errorsTemp.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not save new Shipping Address." );
                errorsTemp.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Shipping Details ");
                session.setAttribute( SessionKeys.ERROR_REPORT, se );

            }
            finally
            {
                if( success == true )
                    dbTransaction.commit();
                else
                    dbTransaction.rollback();
            }
            /*if( !errorsTemp.isEmpty() )
            {
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            }*/

            return( mapping.findForward( "success" ) );
        }

		// Report any errors we have discovered back to the original form
		if( !errors.empty() )
        {
			saveErrors( request, errors );
			return( new ActionForward( mapping.getInput()  ) );
		}


        //Please look at this return later(Where do we need this retrurned) ????
		return( mapping.findForward( "success" ) );

    }
}
